package com.fcscs.cservice.client.main.configuration.reservation;

import java.util.List;

import com.extjs.gxt.ui.client.event.ButtonEvent;
import com.extjs.gxt.ui.client.event.Events;
import com.extjs.gxt.ui.client.event.FieldEvent;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.event.SelectionChangedEvent;
import com.extjs.gxt.ui.client.event.SelectionChangedListener;
import com.extjs.gxt.ui.client.event.SelectionListener;
import com.extjs.gxt.ui.client.store.ListStore;
import com.extjs.gxt.ui.client.widget.HorizontalPanel;
import com.extjs.gxt.ui.client.widget.Label;
import com.extjs.gxt.ui.client.widget.LayoutContainer;
import com.extjs.gxt.ui.client.widget.MessageBox;
import com.extjs.gxt.ui.client.widget.VerticalPanel;
import com.extjs.gxt.ui.client.widget.form.Field;
import com.extjs.gxt.ui.client.widget.form.FormPanel;
import com.extjs.gxt.ui.client.widget.form.ComboBox.TriggerAction;
import com.extjs.gxt.ui.client.widget.form.FormPanel.LabelAlign;
import com.extjs.gxt.ui.client.widget.form.TextField;
import com.extjs.gxt.ui.client.widget.form.Validator;
import com.extjs.gxt.ui.client.widget.layout.ColumnData;
import com.extjs.gxt.ui.client.widget.layout.ColumnLayout;
import com.fcscs.core.common.authority.CServiceAuthority;
import com.fcscs.core.common.authority.UserAuthority;
import com.fcscs.core.domain.IdNameModel;
import com.fcscs.core.domain.Property;
import com.fcscs.core.gwt.common.AsyncCallbackListener;
import com.fcscs.core.gwt.common.CoreConstants;
import com.fcscs.core.gwt.common.SessionContext;
import com.fcscs.core.gwt.common.ui.CenteredInfo;
import com.fcscs.core.gwt.common.ui.FcsFields.EasyClearCombobox;
import com.fcscs.core.gwt.common.ui.FcsFields.FormButton;
import com.fcscs.core.gwt.common.ui.FcsPanel;
import com.fcscs.cservice.client.common.CServiceConstants;
import com.fcscs.cservice.client.common.controller.ReservationServiceController;
import com.fcscs.cservice.client.common.model.configuration.reservation.PropertyIdNameModelData;
import com.fcscs.cservice.domain.model.ReservationConf;
import com.fcscs.share.gwt.common.ShareGWTConstants;
import com.google.gwt.user.client.ui.Widget;

public class GSAConfigPanel extends FcsPanel {
	private VerticalPanel vp;
	private TextField<String> gsaField;
	private TextField<String> gsaSecField;
	private TextField<String> gsaThdField;
	private ReservationConf currentPropConf;
	private EasyClearCombobox<PropertyIdNameModelData> propCombox;
	private ListStore<PropertyIdNameModelData> propListStore;
	private List<IdNameModel<Property>> propGroupIdNames;

	public GSAConfigPanel(String id) {
		super(id);
	}
	
	private Validator gsaValidator = new Validator() {
		@Override
		public String validate(Field<?> field, final String value) {
			if(value != null && !(value.trim().isEmpty()) && value.trim().length() > 20){
				return ShareGWTConstants.SHARE_GWT_MESSAGES.outOfLength(CServiceConstants.CSERVICE_CONSTANTS.gsa(), 20);
			}

			return null;
		}
	};
	
	private Validator gsaSecValidator = new Validator() {
		@Override
		public String validate(Field<?> field, final String value) {
			if(value != null && !(value.trim().isEmpty()) && value.trim().length() > 20){
				return ShareGWTConstants.SHARE_GWT_MESSAGES.outOfLength(CServiceConstants.CSERVICE_CONSTANTS.gsaSecLang(), 20);
			}

			return null;
		}
	};
	
	private Validator gsaThdValidator = new Validator() {
		@Override
		public String validate(Field<?> field, final String value) {
			if(value != null && !(value.trim().isEmpty()) && value.trim().length() > 20){
				return ShareGWTConstants.SHARE_GWT_MESSAGES.outOfLength(CServiceConstants.CSERVICE_CONSTANTS.gsaThdLang(), 20);
			}

			return null;
		}
	};

	@Override
	public void init() {
		vp = new VerticalPanel();
		vp.setId("PropertyConfigPanel_vpPanel");
		vp.setSpacing(5);
		
		LayoutContainer lc = new LayoutContainer();
		lc.setId("PropertyConfigPanel_lc");
		lc.setLayout(new ColumnLayout());
		
		Label propLabel = new Label(CoreConstants.CORE_CONSTANTS.property() + CoreConstants.REQURIED_FIELD_LABEL);
		propLabel.setId("PropertyConfigPanel_propLabel");
		
		propListStore = new ListStore<PropertyIdNameModelData>();
		propCombox = new EasyClearCombobox<PropertyIdNameModelData>();
		propCombox.setId("PropertyConfigPanel_propCombox");
//		propCombox.setFieldLabel(CoreConstants.CORE_CONSTANTS.property());
		propCombox.setWidth(200);
		propCombox.setDisplayField(CoreConstants.FULLTNAME);
		propCombox.setAllowBlank(false);
		propCombox.setForceSelection(true);
		propCombox.setTriggerAction(TriggerAction.ALL);
		propCombox.setStore(propListStore);
		propCombox.addSelectionChangedListener(new SelectionChangedListener<PropertyIdNameModelData>(){
			@Override
			public void selectionChanged(
					SelectionChangedEvent<PropertyIdNameModelData> se) {
				myClear();
				ReservationServiceController.getINSTANCE().getRsvConf(
						propCombox.getValue().getEntity().getId(), 
						new AsyncCallbackListener<ReservationConf>(){
							@Override
							public void onLogin(String username) {
								ReservationServiceController.getINSTANCE().getRsvConf(
									propCombox.getValue().getEntity().getId(),this);
							}

							@Override
							public void onFailure(Throwable caught) {
								MessageBox.alert(CoreConstants.CORE_MESSAGES.operation(CoreConstants.CORE_CONSTANTS.system(), ShareGWTConstants.SHARE_GWT_CONSTANTS.error()),
									CoreConstants.CORE_CONSTANTS.systemError(), null);
							}

							@Override
							public void onSuccess(ReservationConf result) {
								if(null != result){
//									currentPropConf = result;
									gsaField.setValue(result.getGsa());
									gsaSecField.setValue(result.getGsaSecLang());
									gsaThdField.setValue(result.getGsaThdLang());
								}
							}
							
						});
			}
		});
		
		lc.add(propLabel, new ColumnData(70));
		lc.add(propCombox, new ColumnData(160));
		
		vp.add(lc);
		
		FormPanel panel = new FormPanel();
		panel.setId("RCConfigPanel_panel");
		panel.setFrame(true);
		panel.setHeading(CServiceConstants.CSERVICE_CONSTANTS.gsa());
		panel.setPadding(10);
		panel.setSize(730, 530);
		panel.setLabelAlign(LabelAlign.LEFT);
		panel.setLabelSeparator("");
		panel.setLabelWidth(200);
		panel.setFieldWidth(400);
		
		gsaField = new TextField<String>();
		gsaField.setId("PropertyConfigPanel_Name_gsaField");
		gsaField.setFieldLabel(CServiceConstants.CSERVICE_CONSTANTS.gsa() + CServiceConstants.FIELD_SEP);
		gsaField.setValidator(gsaValidator);
		gsaField.addListener(Events.OnBlur,new Listener<FieldEvent>() {
			@Override
			public void handleEvent(FieldEvent be) {
				String value = gsaField.getValue();
				if(value != null && !(value.trim().isEmpty()) && value.trim().length() > 20){
					gsaField.forceInvalid(ShareGWTConstants.SHARE_GWT_MESSAGES.outOfLength(CServiceConstants.CSERVICE_CONSTANTS.gsa(), 20));
					return;
				}else{
					gsaField.clearInvalid();
					return;
				}
			}
		});
		panel.add(gsaField);
		
		gsaSecField = new TextField<String>();
		gsaSecField.setId("PropertyConfigPanel_Name_gsaSecField");
		gsaSecField.setFieldLabel(CServiceConstants.CSERVICE_CONSTANTS.gsaSecLang() + CServiceConstants.FIELD_SEP);
		gsaSecField.setValidator(gsaSecValidator);
		gsaSecField.addListener(Events.OnBlur,new Listener<FieldEvent>() {
			@Override
			public void handleEvent(FieldEvent be) {
				String value = gsaSecField.getValue();
				if(value != null && !(value.trim().isEmpty()) && value.trim().length() > 20){
					gsaSecField.forceInvalid(ShareGWTConstants.SHARE_GWT_MESSAGES.outOfLength(CServiceConstants.CSERVICE_CONSTANTS.gsaSecLang(), 20));
					return;
				}else{
					gsaSecField.clearInvalid();
					return;
				}
			}
		});
		panel.add(gsaSecField);
		
		gsaThdField = new TextField<String>();
		gsaThdField.setId("PropertyConfigPanel_Name_gsaThdField");
		gsaThdField.setFieldLabel(CServiceConstants.CSERVICE_CONSTANTS.gsaThdLang() + CServiceConstants.FIELD_SEP);
		gsaThdField.setValidator(gsaThdValidator);
		gsaThdField.addListener(Events.OnBlur,new Listener<FieldEvent>() {
			@Override
			public void handleEvent(FieldEvent be) {
				String value = gsaThdField.getValue();
				if(value != null && !(value.trim().isEmpty()) && value.trim().length() > 20){
					gsaThdField.forceInvalid(ShareGWTConstants.SHARE_GWT_MESSAGES.outOfLength(CServiceConstants.CSERVICE_CONSTANTS.gsaThdLang(), 20));
					return;
				}else{
					gsaThdField.clearInvalid();
					return;
				}
			}
		});
		panel.add(gsaThdField);
		
		vp.add(panel);
		
		HorizontalPanel hp = new HorizontalPanel();
		
		FormButton saveButton = new FormButton(CoreConstants.CORE_CONSTANTS.save());
		saveButton.setId("PropertyConfigPanel_saveButton");
		saveButton.setStyleAttribute(CServiceConstants.CSS_MARGINLEFT, "560px");
		saveButton.setSize(60, 30);
		saveButton.addSelectionListener(new SelectionListener<ButtonEvent>(){
			@Override
			public void componentSelected(ButtonEvent ce) {
				if(gsaField.isValid()
				   && gsaSecField.isValid()
				   && gsaThdField.isValid()){
				ReservationServiceController.getINSTANCE().getRsvConf(
							propCombox.getValue().getEntity().getId(), 
							new AsyncCallbackListener<ReservationConf>(){
								@Override
								public void onLogin(String username) {
									ReservationServiceController.getINSTANCE().getRsvConf(
										propCombox.getValue().getEntity().getId(),this);
								}

								@Override
								public void onFailure(Throwable caught) {
									MessageBox.alert(CoreConstants.CORE_MESSAGES.operation(CoreConstants.CORE_CONSTANTS.system(), ShareGWTConstants.SHARE_GWT_CONSTANTS.error()),
										CoreConstants.CORE_CONSTANTS.systemError(), null);
								}

								@Override
								public void onSuccess(ReservationConf result) {
									if(null == result){
										currentPropConf = new ReservationConf();
										currentPropConf.setOrgId(SessionContext.getInstance().getOrgId());
										currentPropConf.setPropertyId(propCombox.getValue().getEntity().getId());
									}else{
										currentPropConf = result;
									}
									currentPropConf.setGsa(gsaField.getValue());
									currentPropConf.setGsaSecLang(gsaSecField.getValue());
									currentPropConf.setGsaThdLang(gsaThdField.getValue());
									
									savePropertyConf(currentPropConf);
								}
								
							});
				}
			}
		});
		hp.add(saveButton);
		
		FormButton clearButton = new FormButton(CoreConstants.CORE_CONSTANTS.clear());
		clearButton.setId("PropertyConfigPanel_clearButton");
		clearButton.setStyleAttribute(CServiceConstants.CSS_MARGINLEFT, "30px");
		clearButton.setSize(60, 30);
//		hp.add(clearButton);
		vp.add(hp);
		
		add(vp);
		onShow();
	}

	@Override
	public UserAuthority getRequiredAuthority() {
		return CServiceAuthority.cSERVICE_CONFIG;
	}

	@Override
	protected Widget getViewPanel() {
		return vp;
	}

	@Override
	public void onShow() {
		loadProperty();
		myClear();
		ReservationServiceController.getINSTANCE().getRsvConf(
			SessionContext.getInstance().getPropertyId(), 
			new AsyncCallbackListener<ReservationConf>(){
				@Override
				public void onLogin(String username) {
					ReservationServiceController.getINSTANCE().getRsvConf(
						SessionContext.getInstance().getPropertyId(),this);
				}

				@Override
				public void onFailure(Throwable caught) {
					MessageBox.alert(CoreConstants.CORE_MESSAGES.operation(CoreConstants.CORE_CONSTANTS.system(), ShareGWTConstants.SHARE_GWT_CONSTANTS.error()),
						CoreConstants.CORE_CONSTANTS.systemError(), null);
				}

				@Override
				public void onSuccess(ReservationConf result) {
					if(null != result){
//						currentPropConf = result;
						gsaField.setValue(result.getGsa());
						gsaSecField.setValue(result.getGsaSecLang());
						gsaThdField.setValue(result.getGsaThdLang());
					}
				}
				
			});

	}

	@Override
	public boolean onHide() {
		myClear();
		return true;
	}

	private void myClear() {
		gsaField.clear();
		gsaSecField.clear();
		gsaThdField.clear();
	}
	
	private void savePropertyConf(final ReservationConf conf){
		ReservationServiceController.getINSTANCE().saveRsvConf(
			conf, new AsyncCallbackListener<ReservationConf>(){
				@Override
				public void onLogin(String username) {
					ReservationServiceController.getINSTANCE().saveRsvConf(
						conf,this);
				}
				@Override
				public void onFailure(Throwable caught) {
					MessageBox.alert(
						CoreConstants.CORE_MESSAGES.operation(CoreConstants.CORE_CONSTANTS.system(), ShareGWTConstants.SHARE_GWT_CONSTANTS.error()),
						CoreConstants.CORE_CONSTANTS.systemError(), 
						null);
				}
				@Override
				public void onSuccess(ReservationConf result) {
					if(result != null){
						CenteredInfo.displayCompleted(CoreConstants.CORE_CONSTANTS.edited());
					}else{
						MessageBox.alert(
								CoreConstants.CORE_MESSAGES.operation(CoreConstants.CORE_CONSTANTS.system(), ShareGWTConstants.SHARE_GWT_CONSTANTS.error()),
								CoreConstants.CORE_CONSTANTS.systemError(), 
								null);
					}
				}
			});
	}
	
	@Override
	public void setFocus() {
		gsaField.focus();
	}
	
	private void loadProperty() {
		propGroupIdNames = SessionContext.getInstance().getPropertyGroup();
		propListStore.removeAll();
		if (0 != propGroupIdNames.size()) {
			int propIndex = 0;
			for (IdNameModel<Property> inm : propGroupIdNames) {
				propListStore.add(new PropertyIdNameModelData(inm));
				if (propIndex == 0) {
					if (SessionContext.getInstance().getPropertyId() == inm.getId()) {
						propIndex = propListStore.getCount() - 1;
					}
				}
			}
			propCombox.setValue(propListStore.getAt(propIndex));
		} else {
			IdNameModel<Property> tempINM = new IdNameModel<Property>(SessionContext.getInstance().getPropertyId(), SessionContext.getInstance().getPropertyName());
			propListStore.add(new PropertyIdNameModelData(tempINM));
			propCombox.setValue(propListStore.getAt(0));
		}
//		propListStore.removeAll();
//		IdNameModel<Property> tempINM = new IdNameModel<Property>(SessionContext.getInstance().getPropertyId(), SessionContext.getInstance().getPropertyName());
//		propListStore.add(new PropertyIdNameModelData(tempINM));
//		propCombox.setValue(propListStore.getAt(0));
//		grid.setCurrentProperty(propListStore.getAt(0));
	}

}
